const { join } = require('path');
const rollup = require('rollup');
const typescript = require('rollup-plugin-typescript');
const { uglify } = require('rollup-plugin-uglify');

// 爬虫目录
const crawlerDir = join(__dirname, '..', 'crawlers');
// 生成目录
const distDir = join(__dirname, '..', 'dist');

/**
 * 当前时间
 */
function now() {
  const dt = new Date();
  dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset());
  return dt
    .toISOString()
    .slice(0, 19)
    .replace('T', ' ');
}

/**
 * 插件
 */
const plugins = [
  typescript(),
  uglify(),
  {
    name: 'replace',
    transformBundle(source, outputOptions, chunk) {
      const name = chunk.entryModule.originalCode.match(/(?<= @name )[^\n]+/)[0];
      const appid = chunk.entryModule.originalCode.match(/(?<= @appid )\d+/)[0];
      return [
        '/**',
        ` * ${name}`,
        ` * @appid ${appid}`,
        ` * @time ${now()}`,
        ' */',
        source,
      ].join('\n');
    },
  },
];

/**
 * 构建方法
 * @param {object} options
 */
async function build({ file }) {
  const bundle = await rollup.rollup({
    input: `${crawlerDir}/${file}`,
    plugins,
  });

  await bundle.write({
    file: `${distDir}/${file.replace('.ts', '.js')}`,
    format: 'iife',
  });

  return now();
}

module.exports = build;
